/**
 * Created by reeves on 2017/1/25.
 */
Template.postEdit.onCreated(function () {
    Session.set('postEditErrors', {});
});
Template.postEdit.helpers({
    errorMessage: function (field) {
        return Session.get('postEditErrors')[field];
    },
    errorClass: function (field) {
        return !!Session.get('postEditErrors')[field] ? 'has-error' : '';
    },
    categoryEqual: function (categoryName) {
        // Template.instance().data是当前Template的根数据对象
        return (Template.instance().data.post.category == categoryName) ? 'selected' : '';
    }
});

Template.postEdit.events({
    'submit form': function (e) {
        e.preventDefault();

        var currentPostId = this.post._id; // 这里的this指的是发送到该页面带有的数据对象，这里包括post和category

        var postProperties = {
            url: $(e.target).find('[name=url]').val(),
            title: $(e.target).find('[name=title]').val(),
            category: $(e.target).find('[name=category]').val() // 添加分类信息
        }

        var errors = validatePost(postProperties);
        if (errors.title || errors.url)
            return Session.set('postEditErrors', errors);

        Posts.update(currentPostId, {$set: postProperties}, function (error) {
            if (error) {
                // 向用户显示错误消息
                throwError(error.reason);
            } else {
                Router.go('postPage', {_id: currentPostId});
            }
        });
    },

    'click .delete': function (e) {
        e.preventDefault();

        if (confirm("Delete this post?")) {
            var currentPostId = this.post._id;
            Posts.remove(currentPostId);
            Router.go('postsList');
        }
    }
});